package com.cat.binaryAnswer;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
*   @description https://leetcode.cn/problems/most-beautiful-item-for-each-query/
*   @author 曲大人的喵
*   @create 2025/8/10 15:21
*   @since JDK17
*/

public class Solution04 {
    static TreeMap<Integer, Integer> map = new TreeMap<>();
    int find(int[][] h, int target) {
        int l = -1, r = h.length, mid;
        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (h[mid][0] <= target) {
                l = mid;
            } else {
                r = mid;
            }
        }
        return l;
    }

    public int[] maximumBeauty(int[][] items, int[] queries) {
        map.clear();
        int n = items.length, m = queries.length, cnt, tot = 0;
        int[] ans = new int[m];
        int[][] h = new int[n][2];
        for (int i = 0; i < n; i++) {   // 这个数字中最大的值
            cnt = map.getOrDefault(items[i][0], 0);
            if (cnt < items[i][1]) {    // 存最大的
                map.put(items[i][0], items[i][1]);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  //
            h[tot][0] = entry.getKey();
            h[tot++][1] = entry.getValue();
        }
        for (int i = 0; i < m; i++) {
            int k = find(h, queries[i]);
            if (k == -1) {
                ans[i] = 0;
            } else {
                ans[i] = h[k][1];
            }
        }
        return ans;
    }
}
